package org.icec.web.core.config;

import java.sql.SQLException;

import javax.sql.DataSource;
import org.beetl.sql.core.ClasspathLoader;
import org.beetl.sql.core.Interceptor;
import org.beetl.sql.core.UnderlinedNameConversion;
import org.beetl.sql.core.db.DBStyle;
import org.beetl.sql.ext.DebugInterceptor;
import org.beetl.sql.ext.spring4.BeetlSqlDataSource;
import org.beetl.sql.ext.spring4.BeetlSqlScannerConfigurer;
import org.beetl.sql.ext.spring4.SqlManagerFactoryBean;
import org.icec.web.core.support.beetlsql.BSQLUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class SystemConfig implements EnvironmentAware{
 
	 private Environment env;
	/*可省略此配置*/
	/*
	 * @Bean("datasource") //@ConfigurationProperties("spring.datasource.druid")
	 * public DataSource dataSource() { return
	 * DruidDataSourceBuilder.create().build(); }
	 */
	@Bean(name = "beetlSqlScannerConfigurer")
	public BeetlSqlScannerConfigurer getBeetlSqlScannerConfigurer() {
		BeetlSqlScannerConfigurer conf = new BeetlSqlScannerConfigurer();
		conf.setBasePackage("org.icec.web.core.sys.dao;${icec.beetlsql.daoPackage}");
		conf.setDaoSuffix("Dao");
		conf.setSqlManagerFactoryBeanName("sqlManagerFactoryBean");
		return conf;
	}

	@Bean(name = "sqlManagerFactoryBean")
	@Autowired
	public SqlManagerFactoryBean getSqlManagerFactoryBean( DataSource datasource)throws SQLException {
		SqlManagerFactoryBean factory = new SqlManagerFactoryBean();
		BeetlSqlDataSource source = new BeetlSqlDataSource();
		source.setMasterSource(datasource);
		factory.setCs(source);
		factory.setInterceptors(new Interceptor[] { new DebugInterceptor() });
		factory.setNc(new UnderlinedNameConversion());
		//根据数据库驱动设置dbstyle
		String dbType =  env.getProperty("icec.beetlsql.dbStyle");
		DBStyle dbStyle= BSQLUtils.getDBStyleFromDriveName(dbType);
		factory.setDbStyle(dbStyle);
		factory.setSqlLoader(new ClasspathLoader("/sql",dbStyle));
		return factory;
	}

	@Override
	public void setEnvironment(Environment environment) {
		this.env=environment;
	}
	

}
